package cn.jlearn.proxy.common.utils;

import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/5/18 5:04 下午
 */
public class CommonThreadFactory implements ThreadFactory {

    private final ThreadGroup threadGroup;

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    public final String namePrefix;

    public CommonThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
        threadGroup = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        if (name == null || "".equals(name.trim())) {
            name = "pool";
        }
        namePrefix = name + "-thread-";
    }

    @Override
    public Thread newThread(@Nullable Runnable r) {
        Thread t = new Thread(threadGroup, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }

}




